export const BASE_URL = "http://121.36.218.91:18803/api/v1"; // 修改为你的后端地址
const request = (options) => {
  uni.showLoading({
    title: "加载中",
  });
  return new Promise((resolve, reject) => {
    // 请求拦截器
    const token = uni.getStorageSync("assecss_token");
    let header = options.header || {};
    let URL = BASE_URL + options.url;
    header["Authorization"] = "JWT " + token;
    uni.request({
      url: URL,
      method: options.method || "get",
      data: options.data || options.params || {},
      header,
      success: (res) => {
        // 响应拦截器
        if (
          res.statusCode === 200 ||
          res.statusCode === 201 ||
          res.statusCode === 204
        ) {
          uni.hideLoading();
          resolve(res.data);
        } else if (res.statusCode == 400) {
          uni.hideLoading();
          uni.$u.toast('请求失败')
          reject(res.data);
        } else if (res.statusCode == 401) {
          uni.hideLoading();
          uni.showToast({
            title: "身份认证过期，请重新登录",
            icon: "none",
          });
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/login/index",
            });
          }, 1500);
          resolve(res.data);
        } else if (res.statusCode == 417) {
          uni.hideLoading();
          uni.showToast({
            title: "系统授权已过期，请联系管理员",
            icon: "none",
          });
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/login/index",
            });
          }, 1500);
          reject(res.data);
        } else if (res.statusCode == 500) {
          uni.hideLoading();
          uni.showToast({
            title: "请求服务有误",
            icon: "none",
          });
          reject(res.data);
        } else {
          uni.hideLoading();
          uni.showToast({
            title: res.data.msg || "请求失败",
            icon: "none",
          });
          reject(res.data);
        }
      },
      fail: (err) => {
        uni.hideLoading();
        uni.showToast({
          title: "网络异常，请稍后重试",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};
export default request;
